package com.loocan.answer.utils

import android.R
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.FragmentActivity
import timber.log.Timber
import java.lang.reflect.Method

/**
 * @author libin
 * @date 2019-10-14
 * Description:
 */
object StatusBarUtils {
    /**
     * 利用反射获取状态栏高度
     *
     * @return
     */
    fun getStatusBarHeight(activity: Activity): Int {
        var result = 0
        // 获取状态栏高度的资源id
        val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = activity.resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 获得 ActionBar 的高度
     *
     * @param context
     * @return
     */
    fun getActionBarHeight(context: Context): Int {
        val tv = TypedValue()
        context.theme.resolveAttribute(R.attr.actionBarSize, tv, true)
        return TypedValue.complexToDimensionPixelSize(tv.data, context.resources.displayMetrics)
    }

    /**
     * 增加View的paddingTop
     */
    fun setPaddingSmart(
        activity: Activity,
        view: View,
    ) {
        val lp: ViewGroup.LayoutParams? = view.layoutParams
        if (lp != null && lp.height > 0) {
            lp.height += getStatusBarHeight(activity)
        }
        view.setPadding(
            view.paddingLeft,
            view.paddingTop + getStatusBarHeight(activity),
            view.paddingRight,
            view.paddingBottom,
        )
    }

    /**
     * 通过设置全屏，设置状态栏透明 导航栏黑色
     *
     * @param activity
     */
    fun setStatusTransparent(activity: Activity?) {
        if (activity == null) return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.window?.let { window ->
                val attributes = window.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation =
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                //                attributes.flags |= flagTranslucentStatus;
                attributes.flags = attributes!!.flags or flagTranslucentNavigation
                window.attributes = attributes

                window.decorView.systemUiVisibility = (
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        )
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
                window.navigationBarColor = Color.TRANSPARENT
            }


        } else {
            activity.window?.let { window ->
                val attributes = window.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation =
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                attributes.flags = attributes.flags or flagTranslucentStatus
                attributes.flags = attributes.flags or flagTranslucentNavigation
                window.attributes = attributes
            }
        }
    }

    /**
     * 设置顶部状态栏透明 导航栏黑色 :多视角使用
     *
     * @param activity
     */
    fun setTopStatusTransparent(activity: Activity?) {
        if (activity == null) return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.window?.let {window->
                val attributes = window.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                //                attributes.flags |= flagTranslucentStatus;
                attributes.flags = attributes.flags or flagTranslucentStatus
                window.attributes = attributes

                window.decorView.systemUiVisibility = (
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        )
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            }


        } else {
            activity.window?.let { window->
                val attributes = window.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                attributes.flags = attributes.flags or flagTranslucentStatus
                attributes.flags = attributes.flags or flagTranslucentNavigation
                window.attributes = attributes
            }
        }
    }

    /**
     * 设置顶部状态栏透明 导航栏黑色 :霸屏使用
     *
     * @param dialog
     */
    fun setTopStatusTransparent(dialog: Dialog?) {
        if (dialog == null) return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            dialog?.window?.let {window->
                val attributes = window?.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                //                attributes.flags |= flagTranslucentStatus;
                attributes?.flags = attributes!!.flags or flagTranslucentStatus
                window.attributes = attributes

                window.decorView.systemUiVisibility = (
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        )
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            }
        } else {
            dialog?.window?.let {window->
                val attributes = window.attributes
                val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                val flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                attributes?.flags = attributes!!.flags or flagTranslucentStatus
                attributes.flags = attributes.flags or flagTranslucentNavigation
                window.attributes = attributes
            }
        }
    }

    // 状态栏黑色
    fun setStatusBarBlack(activity: Activity?) {
        if (activity == null) return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = activity.window

            window?.decorView?.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    )
            window?.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window?.statusBarColor = Color.BLACK
        } else {
            val window = activity.window
            val attributes = window.attributes
            val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            attributes.flags = attributes.flags.or(flagTranslucentStatus) ?: 0
            window.attributes = attributes
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun setLightMode(activity: Activity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            true
        } else {
            false
        } || setMIUIStatusBarDarkIcon(activity, true) || setMeizuStatusBarDarkIcon(activity, true)
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun setDarkMode(activity: Activity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            true
        } else {
            false
        } || setMIUIStatusBarDarkIcon(activity, false) || setMeizuStatusBarDarkIcon(activity, false)
    }

    /**
     * 修改 MIUI V6  以上状态栏颜色
     */
    @SuppressLint("PrivateApi")
    private fun setMIUIStatusBarDarkIcon(
        activity: Activity,
        darkIcon: Boolean,
    ): Boolean {
        val clazz = activity.window.javaClass
        return try {
            val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
            val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
            val darkModeFlag = field.getInt(layoutParams)
            val extraFlagField =
                clazz.getMethod(
                    "setExtraFlags",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType,
                )
            extraFlagField.invoke(activity.window, if (darkIcon) darkModeFlag else 0, darkModeFlag)
            true
        } catch (e: Exception) {
            Timber.e("set MIUI status bar dark icon$e")
            false
        }
    }

    /**
     * 修改魅族状态栏字体颜色 Flyme 4.0
     */
    private fun setMeizuStatusBarDarkIcon(
        activity: Activity,
        darkIcon: Boolean,
    ): Boolean {
        try {
            val lp = activity.window.attributes
            val darkFlag =
                WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
            val meizuFlags = WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
            darkFlag.isAccessible = true
            meizuFlags.isAccessible = true
            val bit = darkFlag.getInt(null)
            var value = meizuFlags.getInt(lp)
            value =
                if (darkIcon) {
                    value or bit
                } else {
                    value and bit.inv()
                }
            meizuFlags.setInt(lp, value)
            activity.window.attributes = lp
            return true
        } catch (e: Exception) {
            Timber.e("set MEIZU status bar dark icon$e")
            return false
        }
    }

    /**
     * 是否有刘海屏
     *
     * @return
     */
    @Deprecated("使用WindowInset")
    fun hasNotchInScreen(activity: Activity): Boolean {
        // android  P 以上有标准 API 来判断是否有刘海屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val windowInsets: WindowInsets? = activity.window?.decorView?.rootWindowInsets
            val displayCutout = windowInsets?.displayCutout
            if (displayCutout != null) {
                val rects: List<Rect> = displayCutout.boundingRects
                // 通过判断是否存在rects来确定是否刘海屏手机
                if (rects.isNotEmpty()) {
                    return true
                }
            }
        } else {
            // 通过其他方式判断是否有刘海屏  目前官方提供有开发文档的就 小米，vivo，华为（荣耀），oppo
            val manufacturer = Build.MANUFACTURER
            return when {
                TextUtils.isEmpty(manufacturer) -> {
                    false
                }

                manufacturer.equals("HUAWEI", ignoreCase = true) -> {
                    hasNotchHw(activity)
                }

                manufacturer.equals("xiaomi", ignoreCase = true) -> {
                    hasNotchXiaoMi()
                }

                manufacturer.equals("oppo", ignoreCase = true) -> {
                    hasNotchOPPO(activity)
                }

                manufacturer.equals("vivo", ignoreCase = true) -> {
                    hasNotchVIVO()
                }

                else -> {
                    false
                }
            }
        }
        return false
    }

    /**
     * 判断vivo是否有刘海屏
     * https://swsdl.vivo.com.cn/appstore/developer/uploadfile/20180328/20180328152252602.pdf
     *
     * @param activity
     * @return
     */
    @SuppressLint("PrivateApi")
    private fun hasNotchVIVO(): Boolean {
        return try {
            val c = Class.forName("android.util.FtFeature")
            val get: Method = c.getMethod("isFeatureSupport", Int::class.javaPrimitiveType)
            get.invoke(c, 0x20) as Boolean
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 判断oppo是否有刘海屏
     * https://open.oppomobile.com/wiki/doc#id=10159
     *
     * @param activity
     * @return
     */
    private fun hasNotchOPPO(activity: Activity): Boolean {
        return activity.packageManager.hasSystemFeature("com.oppo.feature.screen.heteromorphism")
    }

    /**
     * 判断xiaomi是否有刘海屏
     * https://dev.mi.com/console/doc/detail?pId=1293
     *
     * @param activity
     * @return
     */
    @SuppressLint("PrivateApi")
    private fun hasNotchXiaoMi(): Boolean {
        return try {
            val c = Class.forName("android.os.SystemProperties")
            val get: Method =
                c.getMethod("getInt", String::class.java, Int::class.javaPrimitiveType)
            get.invoke(c, "ro.miui.notch", 0) as Int == 1
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 判断华为是否有刘海屏
     * https://devcenter-test.huawei.com/consumer/cn/devservice/doc/50114
     *
     * @param activity
     * @return
     */
    private fun hasNotchHw(activity: Activity): Boolean {
        return try {
            val cl = activity.classLoader
            val HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil")
            val get: Method = HwNotchSizeUtil.getMethod("hasNotchInScreen")
            get.invoke(HwNotchSizeUtil) as Boolean
        } catch (e: Exception) {
            false
        }
    }

    /**
     * ========================================TODO 下个版本优化============================================
     */

//    WindowInsetsCompat.Type.statusBars()
//    WindowInsetsCompat.Type.navigationBars()
//    WindowInsetsCompat.Type.captionBar()
//    WindowInsetsCompat.Type.ime()
//    WindowInsetsCompat.Type.systemGestures()
//    WindowInsetsCompat.Type.mandatorySystemGestures()
//    WindowInsetsCompat.Type.tappableElement()
//    WindowInsetsCompat.Type.displayCutout()
//    WindowInsetsCompat.Type.systemBars()

//    WindowInsetsCompat.Type.ime() //键盘
//    WindowInsetsCompat.Type.statusBars() //状态栏
//    WindowInsetsCompat.Type.navigationBars() //导航栏
//    WindowInsetsCompat.Type.systemBars()  //状态栏、导航栏和标题栏

    /**
     * 全屏
     * @receiver Activity
     */
    fun Activity.hideSystemUI1() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        ViewCompat.getWindowInsetsController(window.decorView)?.let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars())
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    /**
     * 退出全屏
     * @receiver Activity
     */
    fun Activity.showSystemUI1() {
        WindowCompat.setDecorFitsSystemWindows(window, true)
        ViewCompat.getWindowInsetsController(findViewById<FrameLayout>(R.id.content))
            ?.show(WindowInsetsCompat.Type.systemBars())
    }

    /**
     *  显示状态栏
     *  @param isVisible false 表示沉浸，true表示不沉浸
     */
    fun setStatusBarVisible(
        activity: Activity,
        isVisible: Boolean,
    ) {
        val window = activity.window
        WindowCompat.setDecorFitsSystemWindows(window, isVisible)
        WindowInsetsControllerCompat(window, window.decorView).let { controller ->
            if (isVisible) {
                controller.show(WindowInsetsCompat.Type.statusBars())
            } else {
                controller.hide(WindowInsetsCompat.Type.statusBars())
            }
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }

        // 设置专栏栏和导航栏的底色，透明
//        window.statusBarColor = Color.TRANSPARENT
//        window.navigationBarColor = Color.TRANSPARENT
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            window.navigationBarDividerColor = Color.TRANSPARENT
//        }

        // 设置沉浸后专栏栏和导航字体的颜色，
//        ViewCompat.getWindowInsetsController(activity.findViewById<FrameLayout>(android.R.id.content))?.let { controller ->
//            controller.isAppearanceLightStatusBars = isBlack
//            controller.isAppearanceLightNavigationBars = isBlack
//        }

        // 显示状态栏,字体黑色
//        window.statusBarColor = Color.TRANSPARENT //设置底色
//        ViewCompat.getWindowInsetsController(findViewById<FrameLayout>(android.R.id.content))?.let { controller ->
//            controller.show(WindowInsetsCompat.Type.statusBars())
//            controller.isAppearanceLightStatusBars = true//true字体黑色,false白色
//        }

        // 关闭状态栏
//        ViewCompat.getWindowInsetsController(activity.findViewById<FrameLayout>(android.R.id.content))?.hide(WindowInsetsCompat.Type.statusBars())

        // 显示导航栏
//        ViewCompat.getWindowInsetsController(findViewById<FrameLayout>(android.R.id.content))?.let { controller ->
//            controller.show(WindowInsetsCompat.Type.navigationBars())
//            controller.isAppearanceLightNavigationBars = true//true icon黑色,false白色
//        }
    }

    // 隐藏导航栏
    fun FragmentActivity.hideNavigationBars() {
        WindowInsetsControllerCompat(window, window.decorView).let { controller ->
            controller.hide(WindowInsetsCompat.Type.navigationBars())
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    private val FragmentActivity.windowInsetsCompat: WindowInsetsCompat?
        get() = ViewCompat.getRootWindowInsets(findViewById<FrameLayout>(R.id.content))

    // 判断是否显示导航栏
    fun FragmentActivity.hasNavigationBars(): Boolean {
        val windowInsetsCompat = windowInsetsCompat ?: return false
        return windowInsetsCompat.isVisible(WindowInsetsCompat.Type.navigationBars()) &&
                windowInsetsCompat.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom > 0
    }

    // 获取导航栏的高度
    fun FragmentActivity.getNavigationBarsHeight(): Int {
        val windowInsetsCompat = windowInsetsCompat ?: return 0
        return windowInsetsCompat.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
    }

    // 获取状态栏的高度
    fun FragmentActivity.getStatusBarsHeight(): Int {
        val windowInsetsCompat = windowInsetsCompat ?: return 0
        return windowInsetsCompat.getInsets(WindowInsetsCompat.Type.statusBars()).top
    }

    /**
     * 键盘操作
     * @param activity Activity
     */
    @JvmStatic
    fun hideSoftKeyboard(activity: Activity) {
        ViewCompat.getWindowInsetsController(activity.findViewById<FrameLayout>(R.id.content))
            ?.hide(WindowInsetsCompat.Type.ime())
    }

    @JvmStatic
    fun showSoftKeyboard(activity: Activity) {
        ViewCompat.getWindowInsetsController(activity.findViewById<FrameLayout>(R.id.content))
            ?.show(WindowInsetsCompat.Type.ime())
    }
    /**
     * ========================================TODO 下个版本优化============================================
     */
}
